package db

import (
	"time"

	"qkcoupon/errorcode"

	"doubimeizhi.com/utility"
	"github.com/astaxie/beego"
)

var (
	event201705MysqlHelper *utility.MySQLHelper
)

func createEvent201705MySQLHelper() (*utility.MySQLHelper, error) {
	mysqlHost := beego.AppConfig.DefaultString("mysql::mysql_host", "127.0.0.1")
	mysqlPort := beego.AppConfig.DefaultInt("mysql::mysql_port", 4100)
	mysqlUser := beego.AppConfig.DefaultString("activity::mysql_user_activity", "root")
	mysqlPass := beego.AppConfig.DefaultString("activity::mysql_password_activity", "root")
	mysqlDB := beego.AppConfig.DefaultString("activity::mysql_db_activity", "qkcoupon")
	maxOpenConns := beego.AppConfig.DefaultInt("mysql::mysql_maxOpenConns", 10)
	maxIdleConns := beego.AppConfig.DefaultInt("mysql::mysql_maxIdleConns", 5)

	event201705MysqlHelper = utility.NewMySQLHelper(mysqlHost, mysqlPort, mysqlUser, mysqlPass, mysqlDB, maxOpenConns, maxIdleConns)
	if err := event201705MysqlHelper.Ping(); err != nil {
		return nil, err
	}

	return event201705MysqlHelper, nil
}

func GetEvent201705MySQLHelper() (*utility.MySQLHelper, error) {
	if event201705MysqlHelper == nil {
		return createEvent201705MySQLHelper()
	}
	return event201705MysqlHelper, nil
}

func CheckNewUserCoupon(mobile string) (bool, uint) {
	sql := "select mobile from user_coupon_1705 where mobile=?"
	result, err := event201705MysqlHelper.Query(sql, mobile)
	if err != nil {
		return false, errorcode.EC_GL_EXEC_SQL_FAIL
	}
	if len(result) == 0 {
		return true, errorcode.EC_GL_SUCCESS
	}
	return false, errorcode.EC_GL_SUCCESS
}

func RecordNewUserCoupon(ccode string, mobile string, origin int) uint {
	sql := "insert into user_coupon_1705(ccode,mobile,insert_tick,is_old,origin) values(?,?,?,0,?)"
	_, err := event201705MysqlHelper.Exec(sql, ccode, mobile, time.Now().Unix(), origin)
	if err != nil {
		return errorcode.EC_GL_EXEC_SQL_FAIL
	}
	return errorcode.EC_GL_SUCCESS
}

func CheckNewUserCoupon6(mobile string) (bool, uint) {
	sql := "select mobile from new_user_coupon_1705_2 where mobile=?"
	result, err := event201705MysqlHelper.Query(sql, mobile)
	if err != nil {
		return false, errorcode.EC_GL_EXEC_SQL_FAIL
	}
	if len(result) == 0 {
		return true, errorcode.EC_GL_SUCCESS
	}
	return false, errorcode.EC_GL_SUCCESS
}

func RecordNewUserCoupon6(ccode string, mobile string, no int) uint {
	sql := "insert into new_user_coupon_1705_2(ccode,mobile,insert_tick,no) values(?,?,?,?)"
	_, err := event201705MysqlHelper.Exec(sql, ccode, mobile, time.Now().Unix(), no)
	if err != nil {
		return errorcode.EC_GL_EXEC_SQL_FAIL
	}
	return errorcode.EC_GL_SUCCESS
}

func init() {
	if _, err := GetEvent201705MySQLHelper(); err != nil {
		panic("Failed to connect to Mysql!")
	}
}
